import 'dart:async';
import 'dart:io';

// import 'package:camera/camera.dart';
import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/pages/client/client_root_container.dart';
import 'package:chathouse/pages/expert/expert_root_page.dart';
import 'package:chathouse/pages/login/select_role_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/push/chat_house_push.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/web_socket/web_socket_channel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

import 'package:permission_handler/permission_handler.dart';
// import 'package:flutter_app_badger/flutter_app_badger.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
// late List<CameraDescription> cameras;
//入口
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // cameras = await availableCameras();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  Widget? initPage;
  Permission? _permission;
  PermissionStatus _permissionStatus = PermissionStatus.denied;
  @override
  void initState() {
    super.initState();
    init();
    // 必须添加观察者监听
    WidgetsBinding.instance.addObserver(this);
    //初始化極光
    ChatHousePush.instance.initPlatformState();
    checkInternetConnectivity();
    requestPermission(Permission.notification);
  }

  Future<void> requestPermission(Permission permission) async {
    final status = await permission.request();

    setState(() {
      print(status);
      _permissionStatus = status;
      print(_permissionStatus);
    });
  }


  void checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.none) {
      // 没有网络连接
    } else if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
      // 有网络连接
    }

    // 监听网络变化
    StreamSubscription<ConnectivityResult> subscription;
    subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.none) {
        // 断网
      } else if (result == ConnectivityResult.mobile || result == ConnectivityResult.wifi) {
        //有网了
        MyWebSocketChannel.instance.initSocket();
      }
    });
  }



  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        MyWebSocketChannel.instance.initSocket();
        LogUtil.d("页应用进入前台======$state");
        break;
      case AppLifecycleState.paused:
        LogUtil.d("应用处于不可见状态后台======$state");
        break;
      case AppLifecycleState.inactive:
        LogUtil.d("应用处于不可见状态后台======$state");
        break;
      case AppLifecycleState.detached:
        LogUtil.d("当前页面即将退出======");
        break;
    }
  }

  @override
  void dispose() {
    super.dispose();
    //页面销毁时，移出监听者
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        designSize: const Size(412, 796),
        builder: (context, build) {
          return RefreshConfiguration(
            //全局配置上拉刷新下拉加载请求头尾
            footerTriggerDistance: 15,
            dragSpeedRatio: 0.91,
            enableLoadingWhenNoData: false,
            enableRefreshVibrate: false,
            enableLoadMoreVibrate: false,
            shouldFooterFollowWhenNotFull: (state) {
              // If you want load more with noMoreData state ,may be you should return false
              return true;
            },
            child: GetMaterialApp(
              key: navigatorKey,
              debugShowCheckedModeBanner: false,
              theme: ThemeData(
                textTheme: const TextTheme(
                    headline1: TextStyle(
                        color: Color(Styles.FF333333),
                        fontSize: 16,
                        height: 1.37)),
                appBarTheme: const AppBarTheme(
                  backgroundColor: Colors.transparent,
                  elevation: 0,
                  // iconTheme:
                  // IconThemeData(color: Colors.white, opacity: 0.0),
                  // titleTextStyle: TextStyle(
                  //     color: Styles.c_333,
                  //     fontSize: Styles.f17,
                  //     fontWeight: Styles.W6),
                ),
                scaffoldBackgroundColor: Colors.white,
              ),
              home: initPage,
              defaultTransition: Transition.fade,
              // builder:EasyLoading.init(),
              builder: (context, widget) {
                widget = easyLoad(context, widget);
                widget = MediaQuery(
                  //设置文变字大小不随系统设置改
                  data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                  child: widget,
                );
                return widget;
              },
            ),
          );
        });
  }

  final easyLoad = EasyLoading.init();

  //初始化
  Future<void> init() async {
    initPage = Container();
    // initPage = const LaunchPage();
    //設置緩存角色
    await SpUtil.getInstance();
    String userRole = SpUtil.getString(Keys.userRole);
    AppConstant.userRole = userRole == "c" ? UserRole.c : UserRole.b;
    debugPrint("init - userRole=$userRole");
    //獲取token
    String token = SpUtil.getString(Keys.token);
    AppConstant.token = token;
    debugPrint("init - token=$token");
    //初始化頁面
    var homePage = AppConstant.userRole == UserRole.c
        ? const ClientRootPage()
        : const ExpertRootPage();
    initPage = token.isEmpty ? const SelectRolePage() : homePage;
    setState(() {});
  }
}
